package com.example.phonestore.service.impl;

import com.example.phonestore.entity.Cart;
import com.example.phonestore.entity.Product;
import com.example.phonestore.entity.showCart;
import com.example.phonestore.mapper.CartMapper;
import com.example.phonestore.mapper.ProductMapper;
import com.example.phonestore.service.CartService;
import com.example.phonestore.service.ProductService;
import com.example.phonestore.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;
    @Override
    public JsonResult insertCart(Cart cart) {
        JsonResult jsonResult=new JsonResult();
        Cart cart1=cartMapper.findByUidAndPid(cart.getUid(),cart.getPid());
        if (cart1==null){
            Product product=productMapper.findByProductId(cart.getPid());
            cart.setPrice(product.getPrice());
            Integer r=cartMapper.insertCart(cart);
            if (r==1){
                return JsonResult.success();
            }else {
                jsonResult.setMsg("添加到购物车失败");
                return jsonResult;
            }
        }
        Integer num1=cart1.getNum()+cart.getNum();
        Integer i=cartMapper.updateNumByCid(cart1.getCid(),num1);
        if (i==1){
            return JsonResult.success();
        }
        jsonResult.setMsg("添加到购物车失败");
        return jsonResult;

    }

    @Override
    public List<showCart> getShowCartByUid(Integer uid) {
        List<showCart> list=cartMapper.showCartByUid(uid);
        System.out.println(list);
        return list;
    }

    @Override
    public Integer updateCartNum(Integer cid,Integer uid) {
        System.out.println(cid);
        Cart cart=cartMapper.findByCid(cid);
        System.out.println(cart);
        Integer num=cart.getNum()+1;
        cartMapper.updateNumByCid(cid,num);
        return num;
    }

    @Override
    public JsonResult deleteCartOne(Integer cid) {
        Integer r=cartMapper.deleteCartOne(cid);
        JsonResult jsonResult=new JsonResult();
        if (r==1){
            return JsonResult.success();
        }
        jsonResult.setMsg("删除失败！");
        return jsonResult;
    }

    @Override
    public Integer reduceCartNum(Integer cid,Integer uid) {

        Cart cart=cartMapper.findByCid(cid);

        Integer num=cart.getNum()-1;
        cartMapper.updateNumByCid(cid,num);
        return num;
    }


}
